package binding

import (
	"encoding/json"
	"io/ioutil"
	"net/http"
)

//http数据自动绑定
//
func HttpBindQuery(r *http.Request, objectPtr interface{}) error {
	var querys = make(map[string]interface{})
	for k, v := range r.URL.Query() {
		if len(v) > 0 {
			querys[k] = v[0]
		}
	}
	return Bind(objectPtr, querys).Error()
}

func HttpBindForm(r *http.Request, objectPtr interface{}) error {
	var forms = make(map[string]interface{})
	r.ParseForm()
	for k, v := range r.Form {
		if len(v) > 0 {
			forms[k] = v[0]
		}
	}
	return Bind(objectPtr, forms).Error()
}

func HttpBindHead(r *http.Request, objectPtr interface{}) error {
	var heads = make(map[string]interface{})
	for k, v := range r.Header {
		if len(v) > 0 {
			heads[k] = v[0]
		}
	}
	return Bind(objectPtr, heads).Error()
}

func HttpBindCookie(r *http.Request, objectPtr interface{}) error {
	var cookies = make(map[string]interface{})
	for _, v := range r.Cookies() {
		cookies[v.Name] = v.Value
	}
	return Bind(objectPtr, cookies).Error()
}

func HttpBindJSON(r *http.Request, objectPtr interface{}) error {
	bytes, _ := ioutil.ReadAll(r.Body)
	var data map[string]interface{}
	if err := json.Unmarshal(bytes, &data); err != nil {
		return err
	}
	return Bind(objectPtr, data).Error()
}
